package com.hsogoo.avatar.transport.netty;

import com.google.gson.Gson;
import com.hsogoo.avatar.model.AvatarRequest;
import com.hsogoo.avatar.model.AvatarResponse;
import com.hsogoo.avatar.transport.AvatarChannel;
import com.hsogoo.avatar.transport.AvatarConnectionManager;
import com.hsogoo.avatar.transport.AvatarFuture;

import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;

/**
 * @Author huangsaigang
 * Created @2018/9/29.
 */
public class AvatarNettyChannel implements AvatarChannel {

    private final Channel channel;
    private AvatarConnectionManager connectionManager;
    private EventLoopGroup worker;


    public AvatarNettyChannel(Channel channel){
        this.channel = channel;
    }

    public AvatarNettyChannel(Channel channel, AvatarConnectionManager manager, EventLoopGroup worker){
        this.channel = channel;
        this.connectionManager = manager;
        this.worker = worker;
    }

    @Override
    public AvatarResponse sendRequest(AvatarRequest request) {
        channel.writeAndFlush(request);
        AvatarFuture af = new AvatarFuture(request);
//        try {
//            channel.closeFuture().sync();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            connectionManager.cancelAllAutoReconnect();
//            worker.shutdownGracefully().syncUninterruptibly();
//        }
        return af.get();
    }

    @Override
    public void sendResponse(AvatarResponse response) {
        channel.writeAndFlush(response);
    }
}
